import sys
import blue
import uix
import uiutil
import triui
import xtriui
import listentry
import spiffy
import form
import util
import uthread
import uicls
import uiconst
from service import Service, ROLEMASK_ELEVATEDPLAYER

class TypeDBEntry(listentry.Generic):
    __guid__ = 'listentry.TypeDBEntry'

    def GetMenu(self, *args):
        row = self.sr.node.invtype
        catID = cfg.invgroups.Get(row.groupID).categoryID
        menu = [['Preview',
          lambda *x: uthread.new(sm.StartService('preview').PreviewType, row.typeID),
          ()],
         [('Copy typeID (%s)' % row.typeID),
          lambda *x: blue.pyos.SetClipboardData(str(row.typeID)),
          ()],
         [('Copy groupID (%s)' % row.groupID),
          lambda *x: blue.pyos.SetClipboardData(str(row.groupID)),
          ()],
         [('Copy categoryID (%s)' % catID),
          lambda *x: blue.pyos.SetClipboardData(str(catID)),
          ()],
         ['View market details',
          lambda *x: uthread.new(sm.StartService('marketutils').ShowMarketDetails, row.typeID, None),
          ()],
         None]
        menu += sm.GetService('menu').GetGMTypeMenu(row.typeID)
        return menu




class TypeBrowser(Service):
    __guid__ = 'svc.itemdb'
    __neocommenuitem__ = (('Type Browser', '09_09'),
     'Show',
     ROLEMASK_ELEVATEDPLAYER)

    def __init__(self):
        Service.__init__(self)



    def Show(self):
        self.wnd = wnd = sm.GetService('window').GetWindow('typedb')
        if wnd:
            self.wnd.Maximize()
            return 
        self.wnd = wnd = sm.GetService('window').GetWindow('typedb', create=1)
        wnd.SetWndIcon(None)
        wnd.SetMinSize([350, 270])
        wnd.SetTopparentHeight(0)
        wnd.SetCaption('Type Browser')
        mainpar = uiutil.GetChild(wnd, 'main')
        wnd.sr.tabs = form.TabGroup(uicls.Container(name='tabsparent', parent=mainpar, pos=(0, 0, 0, 0)))
        main = uicls.Container(name='main', parent=mainpar, pos=(const.defaultPadding,
         const.defaultPadding,
         const.defaultPadding,
         const.defaultPadding))
        body = uicls.Container(name='body', parent=main, align=uiconst.TOALL, pos=(0, 0, 0, 0))
        wnd.sr.browser = spiffy.TreeScroll(uicls.Container(name='scroll', parent=body, pos=(0, 0, 0, 0)))
        wnd.sr.browser.multiSelect = False
        wnd.sr.browser.Startup()
        searchParent = uicls.Container(name='search', parent=body, align=uiconst.TOALL, pos=(0, 0, 0, 0))
        searchTop = uicls.Container(name='search', parent=searchParent, height=25, align=uiconst.TOTOP)
        btn = uicls.Button(parent=searchTop, label='Search', func=self.Search, align=uiconst.TORIGHT)
        wnd.sr.input = uicls.SinglelineEdit(name='Search', parent=searchTop, width=-1, left=1, align=uiconst.TOALL)
        uicls.Container(name='div', parent=searchParent, height=5, align=uiconst.TOTOP)
        wnd.sr.input.OnReturn = self.Search
        wnd.sr.scroll = uicls.Scroll(parent=searchParent)
        wnd.sr.scroll.multiSelect = False
        wnd.sr.tabs.Startup([['Browse',
          wnd.sr.browser,
          self,
          0], ['Search',
          searchParent,
          self,
          1]], 'typebrowsertabs')
        self.Search()
        stuff = self.GetContent(None, False)
        wnd.sr.browser.Load(contentList=stuff, headers=['Name', 'typeID'])
        wnd.sr.browser.Sort('Name')



    def GetContent(self, node, newitems = 0):
        if (node is None):
            rows = cfg.invcategories
            level = 1
        elif (node.sublevel == 1):
            rows = [ g for g in cfg.invgroups if (g.categoryID == node.id[1]) ]
            level = 2
        else:
            rows = [ cfg.invtypes.Get(line.typeID) for line in cfg.invtypes if (line.groupID == node.id[1]) ]
            level = 3
        stuff = []
        if (level != 3):
            for row in rows:
                data = {'GetSubContent': self.GetContent,
                 'MenuFunction': self.Menu,
                 'label': row.name,
                 'id': (row.name, row.id),
                 'groupItems': [],
                 'showlen': False,
                 'sublevel': level,
                 'state': 'locked',
                 'selected': 0,
                 'hideExpander': True,
                 'BlockOpenWindow': 1,
                 'hideFill': True}
                stuff.append(listentry.Get('Group', data))

        else:
            for row in rows:
                data = util.KeyVal()
                data.sublevel = 3
                data.label = ('%s<t>%d' % (row.name, row.typeID))
                data.invtype = row
                data.showinfo = 1
                data.typeID = row.typeID
                stuff.append(listentry.Get('TypeDBEntry', data=data))

        return stuff



    def Menu(self, node, *args):
        ids = []
        if (node.sublevel == 1):
            categoryID = node.id[1]
            for typeOb in cfg.invtypes:
                if (typeOb.categoryID == categoryID):
                    ids.append(typeOb.typeID)

        else:
            groupID = node.id[1]
            for typeOb in cfg.invtypes:
                if (typeOb.groupID == groupID):
                    ids.append(typeOb.typeID)


        def _crea(listOftypeIDs, what = '/createitem', qty = 1, maxValue = 2147483647):
            if eve.triapp.uilib.Key(uix.VK_SHIFT):
                result = uix.QtyPopup(maxvalue=maxValue, minvalue=1, caption=what, label=mls.UI_GENERIC_QUANTITY, hint='')
                if result:
                    qty = result['qty']
                else:
                    return 
            for typeID in listOftypeIDs:
                sm.StartService('slash').SlashCmd(('/createitem %d %d' % (typeID, qty)))




        def _load(listOftypeIDs, what = '/load', qty = 1, maxValue = 2147483647):
            if eve.triapp.uilib.Key(uix.VK_SHIFT):
                result = uix.QtyPopup(maxvalue=maxValue, minvalue=1, caption=what, label=mls.UI_GENERIC_QUANTITY, hint='')
                if result:
                    qty = result['qty']
                else:
                    return 
            for typeID in listOftypeIDs:
                sm.StartService('slash').SlashCmd(('/load me %d %d' % (typeID, qty)))



        l = [None,
         ('WM: create all of these', lambda *x: _crea(ids)),
         ('GM: load me all of these', lambda *x: _load(ids))]
        return l



    def Load(self, *args):
        return 



    def Search(self, *args):
        scroll = self.wnd.sr.scroll
        scroll.sr.id = 'searchreturns'
        search = self.wnd.sr.input.GetValue().lower()
        if not search:
            scroll.Load(contentList=[listentry.Get('Generic', {'label': mls.UI_MARKET_PLEASETYPEANDSEARCH})])
            return 
        scroll.Load(contentList=[])
        scroll.ShowHint(mls.UI_GENERIC_SEARCHING)
        matches = sm.GetService('slash').MatchTypes(search, smart=False)
        if matches:
            matches.sort()
            stuff = []
            for (name, rec,) in matches:
                data = util.KeyVal()
                data.label = ('%d<t>%s' % (rec.typeID, rec.name))
                data.invtype = rec
                data.showinfo = 1
                data.typeID = rec.typeID
                stuff.append(listentry.Get('TypeDBEntry', data=data))
                blue.pyos.BeNice()

        else:
            stuff = [listentry.Get('Generic', {'label': (mls.UI_MARKET_NOTHINGFOUNDWITHSEARCH % {'search': search})})]
        scroll.ShowHint()
        scroll.Load(contentList=stuff, headers=['typeID', 'Name'])



    def Hide(self):
        if self.wnd:
            self.wnd.SelfDestruct()
            self.wnd = None




